package com.logic.saas.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.logic.saas.enums.ConstantEnum;
import com.logic.saas.enums.KindEnum;
import com.logic.saas.persistence.QcodeMapper;
import com.logic.saas.pojo.Kind;
import com.logic.saas.pojo.Ps;
import com.logic.saas.pojo.Qcode;
import com.logic.saas.pojo.User;
import com.logic.saas.util.PojoUtil;

@Service
public class QcodeService extends BaseService {

	private Logger logger = Logger.getLogger(QcodeService.class.getName());
	@Autowired
	private QcodeMapper qcodeMapper;
	
	public List<Qcode> getState() throws Exception{
		return this.getQcodesByKindName(KindEnum.STATE.getShortName());
	}
	
	public List<Qcode> getCountry() throws Exception{
		return this.getQcodesByKindName(KindEnum.COUNTRY.getShortName());
	}

	
	public Qcode getQcodeById(Integer id) throws Exception {
		Qcode qcode = null;
		if (id == null) {
			logger.error("id of qcode is null!");
		} else {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", id);
			Ps ps = new Ps(paramMap);
			qcode = qcodeMapper.getQcodeById(ps);
		}
		return qcode;
	}
	
	/**
	 * 根据Kind的shortName 查询code list
	 * @param kindShortName
	 * @return qcodeList code集合
	 * @throws Exception
	 */
	public List<Qcode> getQcodesByKindName(String kindShortName) throws Exception {
		List<Qcode> qcodeList = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("kindShortName", kindShortName);
		Ps ps = new Ps(paramMap);
		qcodeList = qcodeMapper.queryQcodeByKindCode(ps);
		return qcodeList;
	}
	
	public Qcode getQcodeByShortNameAndKind(String kindShortName,String codeShortName) throws Exception {
		Qcode qcode = null;
		if (StringUtils.isNotBlank(kindShortName) && StringUtils.isNotBlank(codeShortName)) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("CODESHORTNAME", codeShortName);
			paramMap.put("KINDSHORTNAME", kindShortName);
			Ps ps = new Ps(paramMap);
			qcode = qcodeMapper.getQcodeByKindNameAndCodeName(ps);
		}else {
			logger.error("kind Short Name is null!");
		}
		
		return qcode;
	}
	/**
	 * update code, 检查kind是否存在 [已测试]
	 * @param qcode
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateQcode(Qcode qcode) throws Exception {
		boolean updateSuccess = false;
		if(qcode != null && qcode.getId() != null && qcode.getKind()!= null && StringUtils.isNotBlank(qcode.getShortName()) && (qcode.getKind().getId() != null || StringUtils.isNotBlank(qcode.getKind().getShortName()))){
			Map<String, Object> paramMap = new HashMap<String, Object>();

			//kindID为空，通过kindName得到kind的ID，如果得不到则报错
			if(qcode.getKind().getId() == null && StringUtils.isNotBlank(qcode.getKind().getShortName())){
				Kind kind = this.getKindByShortName(qcode.getKind().getShortName());
				if(kind != null && kind.getId() != null){
					qcode.getKind().setId(kind.getId());
				}
			}
			if(qcode.getKind().getId() != null){
				User user = this.getSessionUser();
				if(user != null){
					PojoUtil.setCommonInfo(user.getId(), qcode);
				}
				paramMap.put("qcode", qcode);
				Ps ps = new Ps(paramMap);
				qcodeMapper.updateQcode(ps);
				updateSuccess = true;
			}
		}
		
		return updateSuccess;
	}
	/**
	 * 
	 * @param userId
	 * @param codeId
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean deleteQcode(Integer codeId) throws Exception {
		boolean deleteSuccess = false;
		if(codeId != null){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", codeId);
			Ps ps = new Ps(paramMap);
			qcodeMapper.deleteQcode(ps);
			deleteSuccess = true;
		}
		
		return deleteSuccess;
	}

	/**
	 * 为某一kind插入code,如果kind有ID，则直接插入，否则根据kind的shortname查找kind的id，然后插入 - [已测试]
	 * @param qcode
	 * @return
	 * @throws Exception
	 * @author jeffdong
	 */
	@Transactional(readOnly=false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Integer insertQcode(Qcode qcode) throws Exception {
		Integer newId = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if(qcode != null && StringUtils.isNotBlank(qcode.getShortName()) && qcode.getKind() != null && ( qcode.getKind().getId() != null || StringUtils.isNotBlank(qcode.getKind().getShortName()))){
			//kindId为空，根据kind的shortName查找kind的ID
			if(qcode.getKind().getId() == null && StringUtils.isNotBlank(qcode.getKind().getShortName())){
				Kind kind = this.getKindByShortName(qcode.getKind().getShortName());
				Integer kindId ;
				if(kind != null && kind.getId() != null){
					kindId = kind.getId();
				}else{
					//先插入Kind，得到kindID，然后执行
					kind = qcode.getKind();
					kindId = this.insertKind(kind);
				}
				if(kindId != null){
					qcode.getKind().setId(kindId);
				}
			}
			if(qcode.getKind().getId() != null){
				//判断是否有重复记录-code
				paramMap = new HashMap<String, Object>();
				paramMap.put(ConstantEnum.POJONAME.getValue(), qcode);
				Ps psCheck = new Ps(paramMap);
				boolean recordExist = qcodeMapper.ifRecordExist(psCheck);
				if(recordExist){
					this.setErrorMesssage("error.same_record_already_exists");
				}else{
					paramMap = new HashMap<String, Object>();
					User user = this.getSessionUser();
					if(user != null){
						PojoUtil.setCommonInfo(user.getId(), qcode);
					}else{
						PojoUtil.setCommonInfo(1, qcode);
					}
					paramMap.put("qcode", qcode);
					Ps ps = new Ps(paramMap);
					qcodeMapper.insertQcode(ps);
					if (qcode != null && qcode.getId() != null) {
						newId = qcode.getId();
					}
				}
			}else{
				this.setErrorMesssage("invalid kind");
				logger.error("kind id is enpty");
			}
		}

		return newId;
	}
	
	@Transactional(readOnly=false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Integer insertKind(Kind kind) throws Exception{
		Integer newId = null;
		if(kind != null && StringUtils.isNotBlank(kind.getShortName())){
			//判断是否有重复记录
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put(ConstantEnum.POJONAME.getValue(), kind);
			Ps psCheck = new Ps(paramMap);
			boolean recordExist = qcodeMapper.ifRecordExist(psCheck);
			if(recordExist){
				this.setErrorMesssage("error.same_record_already_exists");
			}else{
				paramMap = new HashMap<String, Object>();
				User user = this.getSessionUser();
				if(user != null){
					PojoUtil.setCommonInfo(user.getId(), kind);
				}
				paramMap.put("kind", kind);
				Ps ps = new Ps(paramMap);
				qcodeMapper.insertKind(ps);
				if (kind != null && kind.getId() != null) {
					newId = kind.getId();
				}
			}
		}
			
		return newId;
	}
	
	
	
	public Kind getKindByShortName(String code) throws Exception {
		Kind kind = null;
		if (StringUtils.isBlank(code)) {
			logger.error("Kind code is null!");
		} else {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("SHORTNAME", code);
			Ps ps = new Ps(paramMap);
			kind = qcodeMapper.getKindByShortName(ps);
		}
		return kind;
	}
	
	public Kind getKindById(Integer id) throws Exception {
		Kind kind = null;
		if (id == null) {
			logger.error("id of qcode is null!");
		} else {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", id);
			Ps ps = new Ps(paramMap);
			kind = qcodeMapper.getKindById(ps);
		}
		return kind;
	}
}
